package com.quark.controller.system;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.captcha.generator.RandomGenerator;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author 张高昌
 * @date 2021/12/12 9:30
 * @description TODO
 */
@Api(tags = "验证码")
@RestController
@RequiredArgsConstructor
public class ImgCodeController {

    @ApiOperation("获取验证码")
    @GetMapping("/imgCode")
    public void getCode(HttpServletResponse response, HttpSession session) {
        // 随机生成 4 位验证码
        RandomGenerator randomGenerator = new RandomGenerator("0123456789abcdefghmnpqrstuvwxyz", 4);
        // 定义图片的显示大小
        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(100, 30);
        response.setDateHeader("Expires",0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.setHeader("Pragma","no-cache");
        response.setContentType("image/jpeg");
        try {
            // 调用父类的 setGenerator() 方法，设置验证码的类型
            captcha.setGenerator(randomGenerator);
            // 输出到页面
            captcha.write(response.getOutputStream());
            String code = captcha.getCode();
            session.setAttribute("code",code);
            // 关闭流
            response.getOutputStream().close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
